#pragma once
#include <iostream>
#include <sys/types.h>
#include <string>
#include <string.h>
#include <unistd.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <stdarg.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>

uint16_t defaultport=8080;
std::string defaultip="192.168.58.130";
int size=1024;

class Udpserver{
public:
    Udpserver(const uint16_t &port=defaultport,const std::string &ip = defaultip)
            :_port(port),_ip(ip),_isrunning(false)
    {}
    void Init()
    {
        _sockfd=socket(AF_INET,SOCK_DGRAM,0);
        if(_sockfd<0)
        {
            perror("socket:");
            exit(1);
        }

        struct sockaddr_in local;
        bzero(&local,sizeof(local));
        local.sin_family=AF_INET;
        local.sin_port=htons(_port);
        local.sin_addr.s_addr=_ip.empty() ? INADDR_ANY : inet_addr(_ip.c_str());

        int k=bind(_sockfd,(const struct sockaddr*)(&local),sizeof(local));
        if(k<0)
        {
            perror("bind:");
            exit(1);
        }
    }

    void Run()
    {
        _isrunning=true;
        char inbuff[size];
        while(_isrunning)
        {
            struct sockaddr_in client;
            socklen_t len=sizeof(client);
            ssize_t n=recvfrom(_sockfd,inbuff,sizeof(inbuff)-1,0,(struct sockaddr*)&client,&len);
            if(n<0)
            {
                continue;
            }

            inbuff[n]=0;
            std::string info=inbuff;
            std::string echo_string="server echo# "+info;

            std::cout<<echo_string<<std::endl;

            sendto(_sockfd,echo_string.c_str(),echo_string.size(),0,(struct sockaddr*)&client,len);

        }
    }

    ~Udpserver()
    {
        if(_sockfd>0)
            close(_sockfd);
    }
private:
    int _sockfd;
    uint16_t _port;
    std::string _ip;
    bool _isrunning;
};
